import { defineStore } from 'pinia'
import { ref } from 'vue'
import { getTags, addTag, updateTag, deleteTag, refreshTags } from '@/api/tag'

export const useTagStore = defineStore('tag', () => {
    const loading = ref(false)

    // 获取标签列表
    const fetchTags = async (params) => {
        loading.value = true
        try {
            const { data } = await getTags(params)
            return data
        } catch (error) {
            throw error
        } finally {
            loading.value = false
        }
    }

    // 新增标签
    const fetchAddTag = async (tagData) => {
        loading.value = true
        try {
            const { data } = await addTag(tagData)
            return data
        } catch (error) {
            throw error
        } finally {
            loading.value = false
        }
    }

    // 更新标签
    const fetchUpdateTag = async (id, tagData) => {
        loading.value = true
        try {
            const { data } = await updateTag(id, tagData)
            return data
        } catch (error) {
            throw error
        } finally {
            loading.value = false
        }
    }

    // 刷新缓存
    const fetchRefreshTags = async () => {
        loading.value = true
        try {
            const { data } = await refreshTags()
            return data
        } catch (error) {
            throw error
        } finally {
            loading.value = false
        }
    }

    // 删除标签
    const fetchDeleteTag = async (id) => {
        loading.value = true
        try {
            await deleteTag(id)
        } catch (error) {
            throw error
        } finally {
            loading.value = false
        }
    }

    return {
        loading,
        getTags: fetchTags,
        addTag: fetchAddTag,
        updateTag: fetchUpdateTag,
        deleteTag: fetchDeleteTag,
        fetchRefreshTags
    }
})